import shop from '../api/shop'
import * as types from '../constants/ActionTypes'

function receiveProducts(propucts){
	return {
		type:types.RECEIVE_PRODUCTS,
		products:propucts
	}
}
const receiveProducts=receiveProducts(propucts);

//得到所有产品
export const getAllProducts=function(){
	return function(dispatch){
		shop.getProducts(function(products){
		dispatch(receiveProducts(propucts))
		})
	}	
}

const addToCartUnsafe=function(productId){
	return {
		type:types.ADD_TO_CART,
		productId  //得到dispatch发送的数据
	}
}

//增加产品  只有库存大于0时
export const addToCart=function(productId){
	return function(dispatch, getState){
		if(getState().products.byId[productId].inventory>0){
			dispatch(addToCartUnsafe(productId))
		}
	}
}

//当有买入或卖出时都会checkout
export const checkout=function(products){
	return function(dispatch,getState){
		const {cart} =getState()

		dispatch({
			type:types.CHECKOUT_REQUEST
		})
		shop.buyProducts(products,function(){
			dispatch({
				type:types.CHECKOUT_SUCCESS,
				cart
			})
		})
	}
}